import {currentMenuKey, tagsKey} from "@/config/constant";

export default {
    namespaced: true,
    state: {
        // 当前选中菜单
        get currentMenu() {
            return localStorage.getItem(currentMenuKey);
        },
        set currentMenu(currentMenu) {
            localStorage.setItem(currentMenuKey, currentMenu);
        },
        // 头标签 (如果本地有,就直接使用,如果没有就默认首页)
        get tags() {
            if (localStorage.getItem(tagsKey) === null) {
                // 创建一个对象存储进入本地
                localStorage.setItem(tagsKey, JSON.stringify([{title: "首页", name: "home"}]))
            }
            return JSON.parse(localStorage.getItem(tagsKey));
        },
        set tags(tags) {
            localStorage.setItem(tagsKey, JSON.stringify(tags));
        },
        // 切换侧边栏 判断是否为移动设备
        asideStatus: window.matchMedia("(max-width: 767px)").matches
    },
    mutations: {
        SET_CURRENT_MENU(state, currentMenu) {
            state.currentMenu = currentMenu;
        },
        REMOVE_TAG(state, name) {
            state.tags = state.tags.filter(item => item.name !== name);
        },
        // 后期添加需求 （ 本地存储 tags ）
        ADD_TAG(state, tag) {
            // 获取本地存储
            let tags = state.tags;
            // 添加一个标签
            tags.push(tag);
            // 调用set方法
            state.tags = tags;
        },
        TOGGLE_ASIDE(state) {
            state.asideStatus = !state.asideStatus;
        }
    },
    actions: {
        addTag({state, commit}, tag) {
            // 如果里面不存在就添加
            if (!state.tags.some(item => item.title === tag.title)) {
                commit("ADD_TAG", {title: tag.title, name: tag.name});
            }
        },
        deleteTag({state, commit}, name) {
            // 如果长度 大于一 才删除
            // debugger
            if (state.tags.length > 1) {
                state.tags.forEach((item, index) => {
                    if (state.currentMenu === name && name === item.name) {
                        // 如果 一样默认往后面走
                        let currentTag = state.tags[index - 1] || state.tags[index + 1];
                        if (currentTag) {
                            state.currentMenu = currentTag.name;
                        }
                    }
                });
                // 最后删除
                commit("REMOVE_TAG", name)
            }
        },
        setCurrentMenu({commit}, menuName) {
            commit("SET_CURRENT_MENU", menuName);
        },
        toggleAside({commit}) {
            commit("TOGGLE_ASIDE")
        }
    }
}

